# coding=utf-8
from sqlalchemy import Integer, String, BigInteger, Column, DateTime, ForeignKey
from sqlalchemy.orm import relationship

from uzwan import db, cache
from uzwan.models.channel import Channel

class Account(db.Model):
    '''
    用户账号
    '''
    __tablename__ = 'accounts'

    id = Column('id', BigInteger, primary_key=True)
    account = Column('account', String(255)) # 账号
    passwd = Column('passwd', String(255)) # 密码，如果是从第三方，如QQ、WeiBo等登陆来的，密码可为空
    coins = Column('coins', Integer) # 剩余金币
    uid = Column('uid', String(255)) # 用户ID（UUID）
    register_time = Column('register_time', DateTime) # 注册时间
    last_login_time = Column('last_login_time', DateTime) # 最后登陆时间
    origin = Column('origin', String(255)) # 用来注册来源，直接登陆？QQ登陆？微博登陆？从游客转换而来？
    channel_id = Column('channel_id', BigInteger, ForeignKey(Channel.id)) # 用户所属渠道
    salt = Column('salt', String(255)) # 密码加密盐值

    connect = relationship('AccountConnect', uselist=False, cascade='save-update, delete', backref='account')

    @staticmethod
    @cache.cached('model:account')
    def get_by_account(self, account):
        return db.session.query(Account).filter(Account.account == account).first()

    @staticmethod
    def get_by_id(id):
        return db.session.query(Account).get(id)

class AccountConnect(db.Model):
    '''
    第三方登陆oauth来的账号
    '''
    __tablename__ = 'account_connects'

    id = Column('id', BigInteger, primary_key=True)
    token = Column('token', String(255)) # 第三方oauth生成的token
    openid = Column('openid', String(255)) # 第三方的用户ID（比如在腾讯上的ID，在微博上的ID）
    account_id = Column('account_id', BigInteger, ForeignKey(Account.id))
    provider = Column('provider', String(255)) # 第三方登陆厂商，腾讯、微博、豆瓣……

    @staticmethod
    def get_by_openid(openid, provider):
        return db.session.query(AccountConnect).filter(AccountConnect.openid == openid).filter(AccountConnect.provider == provider).first()

class AccountGuest(db.Model):
    '''
    游客账号，游客账号完成绑定后从此表中删除，添加到accounts表中
    '''
    __tablename__ = 'account_guests'

    id = Column('id', BigInteger, primary_key=True)
    uid = Column('uid', String(255)) # 游客ID（UUID）
    channel_id = Column('channel_id', BigInteger, ForeignKey(Channel.id)) # 用户所属渠道
    register_time = Column('register_time', DateTime) # 游客创建时间
    last_login_time = Column('last_login_time', DateTime) # 游客最后登陆时间

    @staticmethod
    def get_by_id(id):
        return db.session.query(AccountGuest).get(id)

class UserStatus(object):
    '''
    存储在Session中的用户状态
    '''

    def __init__(self, id, channel, origin, logined=True, guest=False):
        self.id = id
        self.channel = channel
        self.origin = origin
        self.logined = logined
        self.guest = guest

    def __str__(self):
        return 'User<%s,%s,%s,%s,%s>' % (self.id, self.channel, self.origin, self.logined, self.guest)

not_login_user = UserStatus(-1, None, None, False, False)
